import { ACmd, AHttpCmd } from "../cmd/base.cmd";
import { RespCode } from "../code/index";
import { CmdSignModel } from "../models/index";
import { httpService } from "../services/index";
import Taro from "@tarojs/taro";

class Scheduler {
    private static _instance: Scheduler;
    private cmdMap: Map<string, ACmd>;
    private constructor(
    ) {
        this.cmdMap = new Map();
    }
    public static get Instance() {
        return this._instance || (this._instance = new this());
    }
    private loadingCount: number = 0;

    exe(cmd: ACmd): void {
        let model: CmdSignModel = cmd.req();
        this.cmdMap.set(model.token, cmd);
        if (cmd instanceof AHttpCmd) {
            if (cmd.showLoading()) {
                Taro.showLoading({
                    title: '加载中'
                })
            }
            httpService.sendData(model)
                .then((res) => {
                    res.data.source = JSON.parse(res.data.source)
                    let cmdSign: CmdSignModel = res.data;
                    this.handleWsResp(cmdSign);
                    setTimeout(()=>{
                        Taro.hideLoading()
                    },300)
                    
                }, (reject) => {
                    Taro.hideLoading()
                    let cmdSign = new CmdSignModel();
                    cmd.afterNetErrorDo && cmd.afterNetErrorDo(cmdSign);
                    if (!cmd.afterNetErrorDo) {
                        Taro.showToast({
                            title: '网络异常，请检查网络',
                            duration: 2000,
                            icon: "none"
                        })
                    }
                })
                .catch((error) => {
                    Taro.hideLoading()
                    console.error(error);
                });
        }
    }

    private handleWsResp(cmdSign: CmdSignModel) {
        let cmd: ACmd | undefined = this.cmdMap.get(cmdSign.token);
        if (cmd) {
            if (cmdSign.respCode == RespCode.SUCCESS) {
                cmd.resp(cmdSign);
                cmd.afterRespDo && cmd.afterRespDo(cmd.afterRespData || cmdSign);
            } else {
                cmd.error(cmdSign);
                cmd.afterErrorDo && cmd.afterErrorDo(cmdSign);

                if (!cmd.afterErrorDo) {
                    Taro.showToast({
                        title: cmdSign.msg,
                        duration: 2000,
                        icon: "none"
                    })
                }

            }
        }
        this.cmdMap.delete(cmdSign.token);
    }

}
const instance = Scheduler.Instance;
export default instance;